<template>
  <el-dialog
    :title="props.operType === 'add' ? '新增套餐' : '编辑套餐'"
    v-model="visible"
    width="55%"
    append-to-body
  >
    <div class="combo-dialog">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-form :model="form" :rules="rules" ref="comboRef" label-width="110px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="城市标签" prop="cityName">
                <el-select
                  @change="getTagEnableOptions"
                  :disabled="editDisabled"
                  style="width: 260px"
                  v-model="form.cityName"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in cityNameOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                    style="width: 100%"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="套餐名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入名称" maxlength="10" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="套餐标签" prop="tagId">
                <el-select
                  v-model="form.tagId"
                  class="m-2"
                  multiple
                  placeholder="请选择标签"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in tagEnableOptions"
                    :key="item"
                    :label="item.tagName"
                    :value="item.tagId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="套餐缩略图" prop="thumb">
                <ImageUploadByType
                  v-model="form.thumb"
                  :isShowTip="false"
                  :limit="1"
                  :fileSize="10"
                  :validateAspectRatio3To2="true"
                />
                <div>图片比例为600px*400px，请上传 大小不超过 10MB 格式为 png/jpg/jpeg 的文件</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-for="(imgItem, imgIndex) in form.comboDetailImgList" :key="imgIndex">
            <el-col :span="24">
              <el-form-item label="详情图" prop="detailImg">
                <ImageUploadByType
                  v-model="imgItem.info"
                  :limit="5"
                  :fileSize="10"
                  modelType="comboDetail"
                  :isShowTip="false"
                />
                <div>图片的比例750px*440px,请上传 大小不超过 10MB 格式为 png/jpg/jpeg 的文件 </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="套餐介绍图">
                <ImageUploadByType
                  v-model="form.comboInfoImg"
                  :isShowTip="false"
                  :limit="1"
                  :fileSize="10"
                />
                <div>图片比例为750px*8000px，请上传 大小不超过 10MB 格式为 png/jpg/jpeg 的文件</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选择配菜" prop="selected">
                <el-button
                  @click="handleAddFileColumn"
                  size="small"
                  type="primary"
                  style="margin-bottom: 8px"
                  >选择配菜</el-button
                >
                <el-table :data="tableList" max-height="600px">
                  <el-table-column
                    label="配菜名称"
                    align="center"
                    prop="goodsName"
                    :show-overflow-tooltip="true"
                    min-width="120"
                  />
                  <el-table-column
                    label="配菜分类"
                    align="center"
                    prop="goodsTypeName"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="口味"
                    align="center"
                    prop="taste"
                    :show-overflow-tooltip="true"
                  >
                    <template #default="scope">
                      {{
                        props.operType === 'add'
                          ? scope.row.taste
                          : getGoodTasteText(scope.row.taste)
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="数量"
                    align="center"
                    prop="goodsNum"
                    :show-overflow-tooltip="true"
                  >
                    <template #default="scope">
                      <span>{{ scope.row.goodsNum ? scope.row.goodsNum : '1' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="成本价(元)"
                    align="center"
                    prop="costPrice"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="原价(元)"
                    align="center"
                    prop="salePrice"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="保质期(天)"
                    align="center"
                    prop="expireDay"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column label="操作" align="center" fixed="right" min-width="50">
                    <template #default="scope">
                      <el-button link type="primary" @click="delGoods(scope.$index, scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="成本价" prop="costPrice">
                <el-input v-model="form.costPrice" placeholder="请输入">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备小程序价" prop="miniPrice">
                <div style="display: flex; align-items: center">
                  <el-input
                    @blur="disabled = true"
                    :disabled="disabled"
                    v-model="form.miniPrice"
                    placeholder="请输入"
                  >
                    <template #append>元</template>
                  </el-input>
                  <el-icon :size="20" @click="disabled = false">
                    <Edit />
                  </el-icon>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="原价" prop="salePrice">
                <el-input @blur="handleBlur" v-model="form.salePrice" placeholder="请输入">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员价" prop="vipPrice">
                <el-input v-model="form.vipPrice" placeholder="请输入">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="保质期" prop="expireDay">
                <el-input v-model="form.expireDay" placeholder="请输入">
                  <template #append>天</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="加热时长" prop="heatTime">
                <el-input v-model="form.heatTime" placeholder="请输入">
                  <template #append>秒</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="口味" prop="taste">
                <el-select
                  v-model="form.taste"
                  class="m-2"
                  clearable
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in goods_taste"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 营养成分表 -->
          <div>
            <el-col :span="24"> 营养成分表 </el-col>
            <el-row style="margin: 20px 0" :gutter="24">
              <el-col style="color: red; margin-left: 60px" :span="2"> 项目 </el-col>
              <el-col style="color: red" :span="4"> 每100克 </el-col>
              <el-col style="margin-left: 170px" :span="4"> NRV% </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="能量" prop="energy">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    disabled
                    v-model="form.energy"
                    placeholder="请输入"
                  >
                    <template #append>千焦</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="energyNrv">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.energyNrv"
                    placeholder="请输入"
                  >
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="蛋白质" prop="protein">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.protein"
                    @blur="changeBlur"
                    placeholder="请输入"
                  >
                    <template #append>克</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="proteinNrv">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.proteinNrv"
                    placeholder="请输入"
                  >
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="脂肪" prop="fat">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.fat"
                    @blur="changeBlur"
                    placeholder="请输入"
                  >
                    <template #append>克</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="fatNrv">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.fatNrv"
                    placeholder="请输入"
                  >
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="碳水化合物" prop="carbohydrate">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.carbohydrate"
                    @blur="changeBlur"
                    placeholder="请输入"
                  >
                    <template #append>克</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="carbohydrateNrv">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.carbohydrateNrv"
                    placeholder="请输入"
                  >
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="钠" prop="sodium">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.sodium"
                    placeholder="请输入"
                  >
                    <template #append>克</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="sodiumNrv">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.sodiumNrv"
                    placeholder="请输入"
                  >
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <!-- 热量 -->
          <div>
            <el-col :span="24"> 热量相关 </el-col>

            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="套餐克重" prop="weight">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    :controls="false"
                    v-model="form.weight"
                    @blur="changeBlur"
                    placeholder="请输入"
                  >
                    <template #append>g</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="套餐热量" prop="kcal">
                  <el-input
                    type="number"
                    @mousewheel.native.prevent
                    disabled
                    :controls="false"
                    v-model="form.kcal"
                    placeholder="请输入"
                  >
                    <template #append>kcal</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </el-card>
      <el-card v-if="props.operType === 'edit'">
        <template #header>
          <div class="card-header">
            <span>参与的计划</span>
          </div>
        </template>
        <el-row>
          <el-col :span="24">
            <el-table :data="comboPlanList" max-height="400">
              <el-table-column
                label="投放计划"
                align="center"
                prop="cPlanName"
                :show-overflow-tooltip="true"
                min-width="120"
              />
              <el-table-column
                label="投放状态"
                align="center"
                prop="status"
                :show-overflow-tooltip="true"
              >
                <template #default="scope">
                  <dict-tag :options="combo_plan_status" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column
                label="数量"
                align="center"
                prop="num"
                :show-overflow-tooltip="true"
              />
              <!-- <el-table-column label="操作" align="center" fixed="right" min-width="50">
              <template #default="scope">
                <el-button link type="primary" @click="delGoods(scope.$index,scope.row)">删除</el-button>
              </template>
            </el-table-column> -->
            </el-table>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loadingSubmit">{{
          props.operType === 'add' ? '新增' : '更新'
        }}</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog title="选择配菜" v-model="visibleGoods" width="50%" append-to-body>
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="配菜名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入" />
      </el-form-item>

      <el-form-item label="配菜分类" prop="goodsTypeId">
        <el-select v-model="queryParams.goodsTypeId" clearable class="m-2" placeholder="请选择">
          <el-option
            v-for="item in SortOptions"
            :key="item.goodsTypeId"
            :label="item.goodsTypeName"
            :value="item.goodsTypeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button type="primary" @click="getList('search')">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableListAll"
      max-height="600px"
      @selection-change="handleSelectionChange"
      ref="tableAllRef"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        label="配菜名称"
        align="center"
        prop="goodsName"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="配菜分类"
        align="center"
        prop="goodsTypeName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="口味" align="center" prop="taste" :show-overflow-tooltip="true" />
      <el-table-column
        label="成本价(元)"
        align="center"
        prop="costPrice"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="原价(元)"
        align="center"
        prop="salePrice"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="保质期"
        align="center"
        prop="expireDay"
        :show-overflow-tooltip="true"
      />
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeGoodsDialog">取 消</el-button>
        <el-button type="primary" @click="confirmSelected">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import { defineProps, reactive, watch, onMounted, nextTick } from 'vue'
import { getGoodsList } from '@/api/meal/goods'
import { getTagComboList } from '@/api/meal/comboTag'
import {
  addCombo,
  getComboDetail,
  updateCombo,
  getComboImgDetail,
  addComboGoodsLine,
  delComboGoodsLine,
  getComboGoodsLine,
  getComboPlanList
} from '@/api/meal/combo'
import { getSortList } from '@/api/meal/goodsType'
import { accSub } from '@/utils/tools'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const props = defineProps({
  operType: {
    type: String,
    default: 'add'
  },
  TagOptions: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['updateList'])
const { proxy } = getCurrentInstance()
const visible = ref(false)
const loadingSubmit = ref(false)
const { goods_taste, combo_plan_status } = proxy.useDict('goods_taste', 'combo_plan_status')
const editDisabled = computed(() => props.operType === 'edit')

const tagEnableOptions = ref([])
const comboRef = ref()
const tableListAll = ref([])
const tableList = ref([])
const comboPlanList = ref([])
const tableAllRef = ref()
const disabled = ref(true)
const queryParams = ref({
  pageNum: 1,
  pageSize: 1000,
  goodsName: null,
  goodsTypeId: null
})

const getList = (search) => {
  let selectedIds = selected.value.map((item) => item.goodsId)
  getGoodsList(queryParams.value).then((res) => {
    tableListAll.value = res.rows
    if (search === 'search') {
      setTimeout(() => {
        tableListAll.value.forEach((ele) => {
          if (selectedIds.includes(ele.goodsId)) {
            tableAllRef.value.toggleRowSelection(ele, true)
          }
        })
      }, 100)
    }
  })
}

const form = ref({
  name: null,
  tagId: null,
  cityName: null,
  thumb: null,
  costPrice: null,
  salePrice: null,
  miniPrice: null,
  vipPrice: null,
  expireDay: null,
  heatTime: null,
  taste: null,
  comboDetailImgList: [
    {
      resourceType: 1,
      imgType: 2,
      info: null
    }
  ],
  comboInfoImg: null
})
const changeBlur = () => {
  form.value.energy = +form.value.protein * 4 + +form.value.fat * 9 + +form.value.carbohydrate * 4
  form.value.kcal = +((form.value.energy * +form.value.weight) / 418).toFixed(2)
}
const checkImg2 = (rule, value, callback) => {
  let img1 =
    form.value.comboDetailImgList.filter(
      (item) => item.imgType === 2 && item.info && item.info.length > 0
    ) || []
  if (img1.length == 0) {
    callback(new Error('请上传套餐详情图'))
  } else {
    callback()
  }
}

const regex = [
  { required: false, message: '请输入数字或小数(保留3位)', trigger: 'blur' },
  {
    pattern: /^(?:[1-9]\d*(?:\.\d{1,3})?|0\.(?!0{1,3})\d{1,3})$/,
    message: '请输入数字或小数(保留3位)',
    trigger: 'blur'
  }
]
const rules = {
  name: [{ required: true, message: '套餐名称不能为空', trigger: 'blur' }],
  cityName: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
  thumb: [{ required: true, message: '请上传套餐缩略图', trigger: 'blur' }],
  detailImg: [{ required: true, validator: checkImg2, trigger: 'change' }],
  costPrice: [
    { required: true, message: '成本价格不能为空', trigger: 'blur' },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入数字或小数(保留两位)', trigger: 'blur' }
  ],
  salePrice: [
    { required: true, message: '套餐价格不能为空', trigger: 'blur' },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入数字或小数(保留两位)', trigger: 'blur' }
  ],
  miniPrice: [
    { required: true, message: '小程序价格不能为空', trigger: 'blur' },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入数字或小数(保留两位)', trigger: 'blur' }
  ],
  vipPrice: [
    { required: true, message: '会员价不能为空', trigger: 'blur' },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入数字或小数(保留两位)', trigger: 'blur' }
  ],
  expireDay: [
    { required: true, message: '保质期不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  heatTime: [
    { required: true, message: '加热时长不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  taste: [{ required: true, message: '请选择辣度', trigger: 'blur' }],
  energyNrv: regex,
  protein: regex,
  proteinNrv: regex,
  fat: regex,
  fatNrv: regex,
  carbohydrate: regex,
  carbohydrateNrv: regex,
  sodium: regex,
  sodiumNrv: regex,
  weight: regex
}

const visibleGoods = ref(false)
function handleBlur() {
  if (!form.value.salePrice && form.value.salePrice !== 0) {
    form.value.miniPrice = null
    return
  }
  form.value.miniPrice = form.value.salePrice - 12 >= 0 ? accSub(form.value.salePrice, 12) : 0
}
function handleAddFileColumn() {
  queryParams.value.cityName = form.value.cityName
  getList()
  visibleGoods.value = true
  let selectedIds = tableList.value.map((item) => item.goodsId)
  tableListAll.value.forEach((row) => {
    if (selectedIds.includes(row.goodsId)) {
      nextTick(() => {
        tableAllRef.value.toggleRowSelection(row, true)
      })
    } else {
      nextTick(() => {
        tableAllRef.value.toggleRowSelection(row, false)
      })
    }
  })
}
const selected = ref([])
const handleSelectionChange = (val) => {
  selected.value = val
}
const confirmSelected = () => {
  if (props.operType === 'add') {
    tableList.value = selected.value
    visibleGoods.value = false
  } else {
    tableList.value.forEach((element) => {
      delComboGoodsLine(element.comboGoodsId)
    })

    let goodsArrData = selected.value.map((item) => {
      return {
        comboGoodsId: null,
        comboId: currentId.value,
        goodsId: item.goodsId
      }
    })
    addComboGoodsLine(goodsArrData).then(
      (res) => {
        getComboGoodsLine(currentId.value).then((res) => {
          tableList.value = res.data || []
        })
        visibleGoods.value = false
      },
      (error) => {
        proxy.$modal.msgError(error.msg)
      }
    )
  }
}
const closeGoodsDialog = () => {
  selected.value = []
  queryParams.value.goodsName = null
  queryParams.value.goodsTypeId = null
  visibleGoods.value = false
  getList()
}
const delGoods = (index, rows) => {
  if (props.operType === 'add') {
    tableList.value.splice(index, 1)
  } else {
    delComboGoodsLine(rows.comboGoodsId).then((res) => {
      getComboGoodsLine(currentId.value).then(
        (res) => {
          tableList.value = res.data || []
        },
        (error) => {
          proxy.$modal.msgError(res.msg)
        }
      )
    })
  }
}

function submitForm() {
  proxy.$refs['comboRef'].validate((valid) => {
    if (valid) {
      loadingSubmit.value = true
      let imgList = form.value.comboDetailImgList.flatMap((obj) => {
        if (obj.info) {
          return obj.info.map((infoObj) => {
            return {
              id: infoObj.id ? infoObj.id : null,
              comboId: currentId.value,
              imgType: 2,
              resourceType: 1,
              resourceId: infoObj.resourceId,
              resourceUrl: infoObj.resourceUrl ? infoObj.resourceUrl : infoObj.url
            }
          })
        }
      })
      console.log('comboInfoImg', form.value?.comboInfoImg)
      let params = {
        ...form.value,
        tagId: form.value.tagId ? form.value.tagId.join(',') : null,
        thumb: form.value.thumb[0].resourceId,
        comboInfoImg: form.value?.comboInfoImg?.length
          ? form.value?.comboInfoImg[0]?.url
          : form.value?.comboInfoImg,
        comboDetailImgList: imgList,
        goodsIds: tableList.value.map((item) => item.goodsId)
      }
      if (props.operType === 'add') {
        addCombo(params).then(
          (res) => {
            proxy.$modal.msgSuccess('新增成功')
            emit('updateList')
            visible.value = false
          },
          (error) => {
            loadingSubmit.value = false
          }
        )
      } else {
        ElMessageBox.confirm('确认要修改这行数据吗?', '系统提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          center: false
        })
          .then(() => {
            delete params.goodsIds
            updateCombo({ ...params, comboId: currentId.value })
              .then((res) => {
                proxy.$modal.msgSuccess('更新成功')
                emit('updateList')
                visible.value = false
              })
              .catch(() => {
                loadingSubmit.value = false
              })
          })
          .catch(() => {
            loadingSubmit.value = false
          })
      }
    }
  })
}

const currentId = ref()
const SortOptions = ref([])
async function show(type, id) {
  reset()
  //配菜分类

  visible.value = true
  if (type === 'edit') {
    await getDetailData(id)
    console.log(type, form.value.cityName)
    getPlanList(id)
    getTagEnableOptions()
    getSortList({ pageNum: 1, pageSize: 1000, cityName: form.value.cityName }).then((res) => {
      SortOptions.value = res.rows
    })
    currentId.value = id
  } else if (type === 'add') {
    form.value.cityName = id
    console.log(type, form.value.cityName)
    getTagEnableOptions()
    getSortList({ pageNum: 1, pageSize: 1000, cityName: form.value.cityName }).then((res) => {
      SortOptions.value = res.rows
    })
  }
}

async function getDetailData(id) {
  await getComboDetail(id).then((res) => {
    form.value = res?.data
    console.log(form.value)
    form.value.thumb = res?.data.thumbUrl
    form.value.tagId = res.data.tagId
      ? typeof res.data.tagId === 'string'
        ? res.data.tagId.split(',')
        : res.data.tagId
      : null
    getComboImgDetail(id).then((resimgs) => {
      resimgs.data.forEach((element) => {
        element.url = element.resourceUrl
      })
      let arr3 = resimgs.data.filter((item) => item.resourceType === 1 && item.imgType === 2)
      let obj3 = {
        resourceType: 1,
        imgType: 2,
        info: arr3
      }
      form.value.comboDetailImgList = [obj3]
    })
  })
  getComboGoodsLine(id).then((res) => {
    tableList.value = res.data || []
  })
}
function getPlanList(id) {
  getComboPlanList(id).then((res) => {
    comboPlanList.value = res.data || []
  })
}
function getTagEnableOptions() {
  getTagComboList({ pageNum: 1, pageSize: 9999, cityName: form.value.cityName }).then((res) => {
    tagEnableOptions.value = res.rows.filter((item) => item.enable === 1)
  })
}
function getGoodTasteText(taste) {
  const selectedType = goods_taste.value.find((option) => option.value == taste)
  return selectedType ? selectedType.label : null
}

function reset() {
  form.value = {
    name: null,
    tagId: null,
    thumb: null,
    costPrice: null,
    salePrice: null,
    miniPrice: null,
    vipPrice: null,
    expireDay: null,
    heatTime: null,
    comboDetailImgList: [
      {
        resourceType: 1,
        imgType: 2
      }
    ]
  }
  if (comboRef.value) {
    comboRef.value.resetFields()
  }
  tableList.value = []
  loadingSubmit.value = false
}
defineExpose({
  show
})
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item-input {
  margin-bottom: 5px;
}
:deep(.el-input-group__prepend) {
  background-color: #f5f7fa00 !important;
}
:deep(.el-card__body) {
  padding: 15px 20px 10px 20px !important;
}
.combo-dialog {
  height: 800px;
  overflow-y: scroll;
}
</style>
